package service.wx

import org.paic.d.D

import org.slf4j.Logger
import org.slf4j.LoggerFactory

import util.Utils

// 微信用户信息本地化，下次就不用手工授权了
class WxUserLocal {
	static Logger log = LoggerFactory.getLogger(WxUserLocal.class)

	static void update(Map userOuter){
		Map user = Utils.getMapInKeys(userOuter, 'openid,nickname,province,city,sex,headimgurl')

		def dao = D.gen()
		def item = dao.queryMap('select id from wx_user where openid = ? limit 1', [user.openid])
		if(item){
			user.id = item.id
			user.dd = new Date()

			dao.update(user, 'wx_user', null)
		}else{
			dao.add(user, 'wx_user')
		}

		log(user.openid, 'auth-update', '')
	}

	static Map getUserCached(String openid){
		String expireStr = WxSignature.conf.userCacheExpire
		// default 1 hour
		long expire = expireStr ? Long.valueOf(expireStr) : 3600

		def userLocal = getUserByOpenid(openid, expire)
		if(userLocal){
			log.info('get user from local - ' + openid)
			return userLocal
		}else{
			def user = WxApi.getUserInfo(openid)
			if(user.errcode){
				return user
			}else{
				log.info('get user from remote - ' + openid)
				update(user)
				return user
			}
		}
	}

	static Map getUserByOpenid(String openid, long expire){
		def dao = D.gen()

		def item = dao.queryMap('select * from wx_user where openid = ? limit 1', [openid])
		if(!item)
			return null

		// 已经失效了，时间太久了
		if((item.dd.time + expire * 1000) < System.currentTimeMillis()){
			null
		}else{
			item
		}
	}

	static void log(String openid, String type, String msg){
		def dao = D.gen()

		dao.add([openid: openid, type: type, msg: msg], 'wx_user_log')
	}
}
